package com.so206.aop;

import com.alibaba.fastjson.JSON;
import com.so206.utils.IpKit;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 系统动态请求日志输出
 */
@Aspect
@Component
@Order(5)
public class WebLogAop {

    private static final Logger logger = LoggerFactory.getLogger(WebLogAop.class);

    public WebLogAop() {
        logger.info("WebLogAop Init...");
    }

    /**
     * 配置网站信息
     */
    @Pointcut("execution(public * com.so206.controller..*.*(..))")
    public void web_log111() {
    }


    /**
     * 前置通知
     */
    @Before("web_log111()")
    public void doBefore(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest req = attributes.getRequest();
            Map<String, String[]> parameterMap = req.getParameterMap();
            String declaringTypeName = signature.getDeclaringTypeName();
            if (StringUtils.equals(declaringTypeName, "com.ks.web.controller.FilePartialContentController")) {
                return;
            }
            logger.info("-------------- Request Action Report --------------");
            logger.info("Request URL : " + req.getRequestURI());
            logger.info("Method : " + signature.getName());
            logger.info("Class : " + declaringTypeName);
            logger.info("Http Method : " + req.getMethod() + "() Remote Addr : " + IpKit.getRealIp(req));
            logger.info("Params :" + JSON.toJSONString(parameterMap));
            logger.info("------------- " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " -----------------");
        }
    }

    /**
     * 处理完请求返回内容
     */
    @AfterReturning(returning = "ret", pointcut = "web_log111()")
    public void doAfterReturning(Object ret) throws Throwable {
    }


}
